package com.sdd.sg.filter.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: LogPrintGatewayFilterFactory
 * Description: 日志打印
 * date: 2020/7/7
 *
 * @author xugaojun
 */
@Slf4j
@Component
public class LogPrintGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new LogPrintGatewayFilter(config);
    }

    public static class LogPrintGatewayFilter implements GatewayFilter, Ordered {

        private NameValueConfig config;

        public LogPrintGatewayFilter(NameValueConfig config) {
            this.config = config;
        }

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            // fasle 则不打印日志
            if ("false".equals(config.getValue())) {
                return chain.filter(exchange);
            }

            if (log.isInfoEnabled()) {
                log.info("uri ->> {}, param ->> {}",
                        exchange.getRequest().getURI().getPath(),
                        exchange.getRequest().getURI().getQuery());
            }

            return chain.filter(exchange);
        }

        @Override
        public int getOrder() {
            return -200;
        }
    }

}
